const express = require("express");
const router = express.Router();

const {
  loginService,
  updateAdminService,
  updatePasswordService,
} = require("../services/adminServices");
const { ValidationError } = require("../utils/error");
const { formatResponse, analysisToken } = require("../utils/tool");

router.post("/login", async function (req, res, next) {
  // 首先应该有一个验证码的验证
  if (
    req.body.captcha &&
    req.body.captcha.toUpperCase() !== req.session.captcha.toUpperCase()
  ) {
    throw new ValidationError("验证码错误");
  } else if (!req.body.captcha) {
    throw new ValidationError("验证码为空");
  }
  // 假设上面的验证码已经通过了
  const result = await loginService(req.body);
  if (result.token) {
    res.setHeader("authentication", result.token);
  }
  res.send(formatResponse(0, "", result.data));
});

router.get("/whoAmI", async function (req, res, next) {
  const { id, loginId, username } = analysisToken(req.get("Authorization"));
  res.send(
    formatResponse(0, "", {
      loginId,
      username,
      id,
    })
  );
});

router.put("/", async function (req, res, next) {
  res.send(await updateAdminService(req.body));
});

router.put("/updatePassword", async function (req, res, next) {
  res.send(await updatePasswordService(req.body));
});

module.exports = router;
